# Project Architecture - THP Logistics (`official_import`)

> Mục tiêu: Tài liệu kiến trúc để dev/agent mới vào dự án có thể hiểu nhanh, sửa đúng chỗ và mở rộng tính năng an toàn.
>
> Phạm vi: 2 ứng dụng trong workspace
> - `app-api`: Backend API (Django + DRF, truy vấn SQL trực tiếp)
> - `app-web`: Frontend Admin (Vue 2 + Vuex + Vuetify)

---

## 1) Bức tranh tổng thể

```mermaid
flowchart LR
    User[Admin/User trên trình duyệt] --> FE[app-web\nVue 2 + Vuex + Vuetify]
    FE -->|HTTP + Bearer JWT| API[app-api\nDjango 1.11 + DRF]
    API --> DB[(MySQL\nthpglobal)]
    API --> FS[(Local temp files)]
    API --> FBS[(Firebase Storage / Cloud upload APIs)]
```

### Luồng xác thực
1. Frontend gọi `POST /api-token-auth/` để lấy JWT.
2. Frontend lưu token (localStorage/Vuex persisted state).
3. Các request business gắn header `Authorization: Bearer <token>`.
4. Backend xác thực qua `CustomJSONWebTokenAuthentication` + decorator `require_jwt_authent`.

---

## 2) Backend (`app-api`) - Kiến trúc chi tiết

## 2.1 Công nghệ chính
- Django `1.11.x`
- Django REST Framework `3.9`
- JWT auth (`djangorestframework-jwt`)
- DB: MySQL
- Truy vấn dữ liệu: SQL thủ công qua lớp `RDbSql` (SQLAlchemy engine + pymysql)
- Xử lý dữ liệu bảng: pandas

## 2.2 Cấu trúc lớp theo pattern đang dùng

```mermaid
flowchart TD
    URL[DepositAPI/urls.py] --> APIClass[DepositAPI/api/*.py\nViewSet classes]
    APIClass --> BaseApi[BaseApiView]
    APIClass --> ModelClass[DepositAPI/model/*.py]
    ModelClass --> BaseModel[BaseModel]
    BaseModel --> DBLayer[RDbSql / SQL queries]
    DBLayer --> MySQL[(MySQL)]
```

### Vai trò từng tầng
- `DepositAPI/urls.py`
  - Map endpoint -> action của ViewSet (`list`, `retrieve`, `add`, `edit`, `remove`, ...).
- `DepositAPI/api/*.py`
  - API resource theo domain (Customer, Product, Truck, Quote, ...).
  - Thường kế thừa `BaseApiView`, gắn `modelClass` tương ứng.
- `DepositAPI/api/Api.py` (`BaseApiView`)
  - Định nghĩa CRUD/action chuẩn.
  - Parse query params (pagination/sort/filter/quickFilter base64 JSON).
  - Trả response chuẩn thành công/lỗi.
- `DepositAPI/model/*.py`
  - Mỗi file là model thao tác với 1 bảng/nhóm truy vấn.
- `DepositAPI/model/BaseModel.py`
  - CRUD cơ sở + build điều kiện filter + transform kết quả.
  - Không dùng Django ORM cho nghiệp vụ chính.
- `DepositAPI/libs/db/RDbSql.py`
  - Lớp kết nối và execute SQL.
  - Retry khi lỗi mạng/deadlock ở mức kết nối DB.

## 2.3 Quy ước endpoint
- REST-ish theo resource:
  - List/Create: `GET|PUT /api/<resource>/`
  - Detail/Edit/Delete: `GET|POST|DELETE /api/<resource>/<id>`
- Endpoint mở rộng theo nghiệp vụ:
  - Export/import (`/export_list`, `/import`, ...)
  - Report/dashboard (`/api/report/...`, `/api/dashboard/...`)
  - Upload file (`/api/files/...`)

## 2.4 Cấu hình quan trọng
- `DepositAPI/settings.py`
  - DB mặc định local (`localhost:3308`, db `thpglobal`).
  - `ALLOWED_HOSTS = ["*"]`, `CORS_ORIGIN_ALLOW_ALL = True`.
  - `REST_FRAMEWORK.DEFAULT_PERMISSION_CLASSES = IsAuthenticated`.
  - Middleware có `SQLInjectionProtectionMiddleware`.
  - `TEMP_DOWNLOAD_PATH` cho file export tạm.
- JWT custom payload/response nằm ở `DepositAPI/api/models.py`.

## 2.5 Điểm cần lưu ý khi sửa backend
- Luồng chính hiện phụ thuộc SQL string thủ công -> cần cẩn trọng SQL injection/escaping khi thêm query mới.
- Dự án đang để `DEBUG=True` trong settings hiện tại.
- Decorator `require_jwt_authent` và custom JWT auth cùng tham gia auth flow; khi chỉnh auth cần test đồng thời cả 2 lớp.

---

## 3) Frontend (`app-web`) - Kiến trúc chi tiết

## 3.1 Công nghệ chính
- Vue `2.x`
- Vue Router `3.x`
- Vuex `3.x` (+ persisted state)
- Vuetify `2.x`
- HTTP client: `vue-resource`
- i18n tích hợp sẵn

## 3.2 Cấu trúc chức năng

```mermaid
flowchart TD
    Main[src/main.js] --> Router[src/router/*]
    Main --> Store[src/store/*]
    Main --> Plugins[vuetify, i18n, filters, directives]

    Router --> Views[src/views/*]
    Views --> VuexModules[src/store/modules/*]
    VuexModules --> Hpod[src/commons/hpod.js]
    Hpod --> API[app-api /api/*]
```

### Vai trò chính
- `src/main.js`
  - Bootstrap app, đăng ký plugins/filter/directive/global component.
- `src/router/paths.js`
  - Danh sách route + metadata quyền/nút action UI.
- `src/router/index.js`
  - Guard xác thực + kiểm tra phân quyền theo bitmask (`configs.ROLES.modules & route.meta.roleId`).
- `src/store/modules/*`
  - Mỗi module quản lý state/action/mutation theo domain.
- `src/commons/hpod.js`
  - Wrapper gọi API chung (list/detail/create/update/delete/export/upload).
  - Build query filter/pagination và encode base64 theo format backend.
- `src/configs/index.js`
  - Hằng số hệ thống, enum nghiệp vụ, role map, endpoint từ env.

## 3.3 Cấu hình môi trường
- `.env`
  - `VUE_APP_ENDPOINT=http://127.0.0.1:8111`
- `.env.staging`
  - `VUE_APP_ENDPOINT=` (cần cung cấp khi deploy staging)
- `package.json`
  - `npm run dev` chạy port `3001`.

## 3.4 Điểm cần lưu ý khi sửa frontend
- Router đang set `mode` 2 lần trong `router/index.js`; giá trị cuối cùng là `history`.
- Token được lưu localStorage, state auth persisted; cần clear đúng khi logout/auth fail.
- Convention API module/store module đang đồng nhất theo `endpoint` string -> nên giữ pattern này khi thêm tính năng mới.

---

## 4) Luồng dữ liệu chuẩn (End-to-End)

1. User thao tác trên page (`views/*`).
2. Page dispatch action Vuex (`store/modules/*`).
3. Action gọi helper trong `commons/hpod.js`.
4. `hpod.js` gọi backend endpoint `/api/...` kèm JWT.
5. Backend: `urls.py` -> API class -> model class -> SQL -> MySQL.
6. Kết quả trả JSON chuẩn về frontend.
7. Vuex commit mutation, UI render lại.

---

## 5) Cách thêm tính năng mới (chuẩn theo codebase hiện tại)

## 5.1 Backend
1. Tạo/điều chỉnh bảng dữ liệu MySQL.
2. Tạo model trong `DepositAPI/model/` kế thừa `BaseModel`.
3. Tạo API class trong `DepositAPI/api/` kế thừa `BaseApiView` và gán `modelClass`.
4. Khai báo route trong `DepositAPI/urls.py`.
5. Nếu có import/export file: tái sử dụng pattern `UploadFile`/report export hiện có.

## 5.2 Frontend
1. Tạo/chỉnh API wrapper ở `src/api/` hoặc dùng trực tiếp helper trong `commons/hpod.js`.
2. Tạo/chỉnh Vuex module tương ứng trong `src/store/modules/`.
3. Tạo/chỉnh view trong `src/views/`.
4. Khai báo route trong `src/router/paths.js` với `meta.roleId` đúng phân quyền.
5. Đồng bộ key i18n nếu thêm label/title mới.

---

## 6) Bản đồ domain hiện có (high-level)

- Account/User/Auth
- Customer
- Product / Tracking / Storage
- Truck / Order / Bill / BillProduct / TruckProduct
- Recharge / Payment history
- Quote / QuotePackage
- Dashboard + Reports (revenue, debt, truck, ...)
- Audit logs
- File upload (cloud/local fallback)

---

## 7) Runbook nhanh cho dev/agent mới

## 7.1 Backend local
- Tạo virtualenv + cài `requirements.txt`.
- Chuẩn bị MySQL và schema `thpglobal`.
- Kiểm tra cấu hình DB trong `DepositAPI/settings.py`.
- Chạy: `python manage.py runserver 0.0.0.0:8111`.

## 7.2 Frontend local
- Cài node_modules.
- Kiểm tra `VUE_APP_ENDPOINT` trong `.env` trỏ đúng backend.
- Chạy: `npm run dev`.

## 7.3 Kiểm tra tích hợp
- Đăng nhập để lấy JWT.
- Test 1 route list (vd customer/product).
- Test 1 route detail update.
- Test 1 chức năng export/import.

---

## 8) Gợi ý cho agent khi bắt đầu sửa code

1. Xác định domain cần sửa (ví dụ: Quote, Product, Bill).
2. Tìm cặp file theo domain:
   - Backend: `DepositAPI/api/<Domain>.py` + `DepositAPI/model/<Domain>.py`
   - Frontend: `src/store/modules/<domain>.js` + `src/views/<Domain>/...`
3. Kiểm tra endpoint đã map trong `DepositAPI/urls.py`.
4. So khớp tham số filter/pagination theo format `commons/hpod.js`.
5. Nếu lỗi quyền truy cập, kiểm tra `meta.roleId` (router) và `configs.ROLES`.

---

## 9) Phạm vi/giả định của tài liệu

- Tài liệu mô tả kiến trúc theo hiện trạng code trong workspace tại thời điểm tạo.
- Đây là tài liệu thực thi (implementation architecture), không phải tài liệu business requirements.
- Nên cập nhật lại mục 5, 6, 8 khi thêm module hoặc thay đổi pattern kiến trúc lớn.
